/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fanta.framework.dao;

import fanta.framework.manager.ConnectionManager;
import fanta.framework.persistence.Lega;
import fanta.framework.persistence.Team;
import fanta.framework.persistence.Utente;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.EntityManager;
import org.apache.log4j.Logger;

/**
 *
 * @author Claudio Rossi
 */
public class TeamDAO {
     private static final Logger logger = Logger.getLogger(TeamDAO.class);
     static int BUDGET = 500;
    public static Team creaTeam(String nome, Utente owner, Lega lega, int BUDGET, ConnectionManager cm) {
        EntityManager entityManager = (EntityManager) cm.getEntityManager();
        Team team = new Team();
        try {
            entityManager.getTransaction().begin();
            logger.debug("Start Transaction");
            team.setNome(nome);
            team.setOwner(owner);
            team.setLega(lega);
            team.setBudget(BUDGET);
            entityManager.persist(team);
            logger.debug("Transaction persisted");
            entityManager.getTransaction().commit();
            logger.debug("Transaction committed");
            logger.info("New team:"+team);

        } catch (Exception e) {
            logger.error("Errore in TeamDAO", e);
            logger.debug("##EXCEPTION## Transaction will be roll back");
            entityManager.getTransaction().rollback();
            logger.debug("Transaction rolled back!");
        }
        return team;
    }

     public Collection cercaTeamByNome(String nome, ConnectionManager cm) {
        Collection listaTeam = new ArrayList<Team>();
        try {
            EntityManager entityManager = (EntityManager) cm.getEntityManager();
            listaTeam = entityManager.createNamedQuery("Giocatore.findByNome").setParameter("nome", nome).getResultList();
        } catch (Exception e) {
            logger.error("#EXCEPTION# in cercaTeamByNome!", e);
        }
        return listaTeam;
    }

}
